package com.qianfeng.openapi.search.mq;

import com.qianfeng.openapi.search.service.CustomerSearchService;
import com.qianfeng.openapi.search.util.JsonUtil;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;

@Component
public class CustomerListener {

    @Autowired
    private CustomerSearchService customerSearchService;


    @RabbitListener(queues = {"customer-queue"})
    public void listen(Channel channel, Message message) throws IOException {
        //1. 从message中获取消息内容,非空判断
        byte[] body = message.getBody();
        String json = "";
        if(body != null){
            json = new String(body,"UTF-8");
        }

        //2. 获取routingKey判断具体操作
        String s = message.getMessageProperties().getReceivedRoutingKey();
        switch (s){
            case "openapi.customer.add":
                // 添加操作
                customerSearchService.add((Map) JsonUtil.getObj(json, Map.class));
                break;
            case "openapi.customer.update":
                // 修改操作
                break;
            case "openapi.customer.delete":
                // 删除操作
                break;
            default:
                // 记录日志,不知道什么操作
        }
        // 消费完毕,ack
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);

    }


}
